package com.ljph.kit;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ProcessKit {
  
  private static final Logger _log = LoggerFactory.getLogger(ProcessKit.class);
  
  private Object cmdString;
  private String message;
  private String error;
  public Object getCmdString() {
    return cmdString;
  }
  public void setCmdString(Object cmdString) {
    this.cmdString = cmdString;
  }
  public String getMessage() {
    return message;
  }
  public void setMessage(String message) {
    this.message = message;
  }
  public String getError() {
    return error;
  }
  public void setError(String error) {
    this.error = error;
  }
  
  public boolean run() {
    _log.debug("Run process with: " + cmdString);
    
    try {
      Runtime runTime = Runtime.getRuntime();
  
      Process process = null;
      if(cmdString instanceof String) {
        process = runTime.exec((String) cmdString);
      } else if(cmdString instanceof List) {
        process = runTime.exec(((List<String>)cmdString).toArray(new String[0]));
      }
  
      if(!checkProcessOutput(process)) {
        return false;
      }
    } catch (IOException e) {
      _log.error("Run process failed: ", e);
      return false;
    }
    return true;
  }
  
  private boolean checkProcessOutput(Process process) throws IOException {

    String processOutput = readStreamContent(process.getInputStream());
    String processError = readStreamContent(process.getErrorStream());

    _log.debug("The normal output of process: \n" + processOutput);

    if(!processError.isEmpty()) {
      this.error = processError;
      return false;
    }
    this.message = processOutput;
    return true;
  }
  
  public String readStreamContent(InputStream is) throws IOException {

    byte[] c2 = new byte[1024];

    int n = 0;

    StringBuffer content = new StringBuffer();
    while((n = is.read(c2)) > 0) {
        content.append(new String(c2, 0, n, "UTF-8"));
    };

    return content.toString();
}
}
